package me.firstapp.search.controller;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.JsonTopic;
import me.firstapp.common.module.bbs.SearchResult;
import me.firstapp.common.module.shop.JsonProduct;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.search.service.ProductSearchService;
import me.firstapp.search.service.TopicSearchService;

@Controller
public class SearchController {

	@Autowired
	private TopicSearchService topicSearchService;

	@Autowired
	private ProductSearchService productSearchService;

	@PostConstruct
	public void init() {
		topicSearchService.addData();
		productSearchService.addData();
	}

	@RequestMapping(value = "updateData.do", method = RequestMethod.GET)
	public void updateData(HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			topicSearchService.addData();
			productSearchService.addData();
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "search.do", method = RequestMethod.GET)
	public void search(String keyword, HttpServletResponse response) {
		SingleObject<SearchResult> result = new SingleObject<>();
		try {
			List<JsonProduct> products = productSearchService.search(keyword);
			List<JsonTopic> topics = topicSearchService.search(keyword);

			SearchResult sr = new SearchResult();
			sr.setTopics(topics);
			sr.setProducts(products);

			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setObject(sr);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}
}
